<!--
 * @Description: 退货记录
 * 
 * @Author: Edan<Edan>
 * @Date: 2024-08-24 09:10:19
 * @FilePath: /yuxiuproweb/src/views/material/returnRecord/index.vue
-->
<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="出库单号" prop="outboundId">
        <el-input
          v-model="queryParams.outboundId"
          placeholder="请输入出库单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="供应商" prop="supplier">
        <el-input
          v-model="queryParams.supplier"
          placeholder="请输入供应商"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="备注" prop="notes">
        <el-input
          v-model="queryParams.notes"
          placeholder="请输备注"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="出库日期" prop="creatTimeObj">
        <el-date-picker
          align="center"
          style="width: 240px"
          v-model="creatTimeObj"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          format="yyyy-MM-dd"
          @change="handleQuery"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          >导出</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-edit-outline"
          size="mini"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-printer"
          size="mini"
          @click="handlePrint"
          >打印</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          @click="handleDelete"
          >删除</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          >期初导入</el-button
        >
      </el-col> -->
      <el-button type="primary" plain size="mini" @click="handleBatch()"
        >批量操作</el-button
      >
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>
    <el-table
      ref="tableList"
      v-loading="loading"
      :data="list"
      @selection-change="handleSelectionChange"
      :max-height="maxHeight"
      :row-style="{ height: '20px' }"
      :cell-style="{ padding: '4px', 'font-size': '15px' }"
      border
      size="mini"
    >
      <el-table-column type="selection" width="55" align="center" />
      <template v-for="(i, index) in tableForm.item">
        <el-table-column
          :key="index"
          :prop="i.itemcode"
          :columnKey="i.itemcode"
          :label="i.itemname"
          :align="i.aligntype ? i.aligntype : 'center'"
          :min-width="i.minwidth"
          :show-overflow-tooltip="i.overflow ? true : false"
          :sortable="i.sortable ? true : false"
          :width="!!i.width ? i.width : ''"
          :fixed="i.fixed"
          v-if="i.displaymark ? true : false"
        >
          <template slot-scope="scope">
            <el-button
              v-if="i.itemcode == 'outboundId'"
              type="text"
              @click="handlechange(scope.row)"
              >{{ scope.row[i.itemcode] }}</el-button
            >
            <div v-else-if="i.itemcode == 'createTime'">
              <span>{{ scope.row[i.itemcode] | dateFormat }}</span>
            </div>
            <span v-else>{{ scope.row[i.itemcode] }}</span>
          </template>
        </el-table-column>
      </template>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        min-width="120px"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handlechange(scope.row)"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            style="color: #ff4949"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <add-view
      v-if="open.show"
      :show.sync="open.show"
      v-bind="open"
      @update="getList"
    ></add-view>
    <detail-view
      v-if="detailopen.show"
      :show.sync="detailopen.show"
      v-bind="detailopen"
      @update="getList"
    ></detail-view>
    <!-- 打印 -->
    <print-view
      v-if="print.show"
      :show.sync="print.show"
      v-bind="print"
    ></print-view>
    <el-dialog
      :title="'批量操作'"
      :append-to-body="true"
      width="400px"
      :visible.sync="openBatch"
      :close-on-click-modal="false"
      class="paichengDialog"
    >
      <div style="display: flex; align-items: center">
        <span style="width: 60px">领用人</span>
        <el-input v-model="recipient" placeholder="请输入领用人" />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="submitBatch()"
          >确 定</el-button
        >
        <el-button size="small" @click="openBatch = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 期初导入 -->
    <el-dialog
      :close-on-click-modal="false"
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import request from "@/utils/request";
import { tableList } from "./mods/tablecolums.js";
import commonMix from "@/utils/mixins/common";
import PrintView from "./mods/print.vue";
import DetailView from "./mods/detail.vue";
import AddView from "./mods/add.vue";
import { getToken } from "@/utils/auth";
export default {
  name: "logisticsOrder",
  components: {
    AddView,
    PrintView,
    DetailView,
  },
  mixins: [commonMix],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 墙布表格数据
      list: [],
      // 是否显示弹出层
      open: {
        show: false,
        type: "add",
        data: null,
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 100,
        repositoryName: null,
        inventoryCode: null,
        frbaicName: null,
        specification: null,
        unit: null,
        batchNumber: null,
        inventoryQuantity: null,
        availableQuantity: null,
        accurate: false,
        ctype: null,
        outboundId: null,
        supplier: null,
      },
      //
      tableForm: tableList,
      selRow: [],
      creatTimeObj: [],
      print: {
        show: false,
        type: "0",
        data: null,
        supplier: null,
      },
      detailopen: {
        show: false,
        data: null,
      },
      recipient: "",
      openBatch: false,
      warehouseList: [],
      // 导入参数
      upload: {
        // 是否显示弹出层（收入导入）
        open: false,
        // 弹出层标题（收入导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的收入数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/md/outbound/importData",
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询高端定制列表 */
    getList() {
      this.loading = true;
      var queryParams = {
        ...this.queryParams,
        startDate: this.creatTimeObj?.[0] || null,
        endDate: this.creatTimeObj?.[1] || null,
      };
      request({
        url: "/md/outbound/list",
        method: "get",
        params: queryParams,
      }).then((res) => {
        this.list = res.rows;
        this.total = res.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.creatTimeObj = [];
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.outboundId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
      this.selRow = selection;
    },
    // 添加出库单
    handleAdd() {
      this.open = {
        show: true,
        type: "add",
        data: null,
      };
    },
    handlePrint() {
      if (this.selRow.length == 0) {
        this.$message.error("请勾选打印内容");
        return;
      }
      var istrue = true;
      for (let i = 0; i < this.selRow.length; i++) {
        const item = this.selRow[i];
        if (item.supplier != this.selRow[0].supplier) {
          istrue = false;
          break;
        }
      }
      if (istrue) {
        this.print = {
          show: true,
          type: "0",
          data: this.selRow,
          supplier: this.selRow[0].supplier,
        };
      } else {
        this.$message.error("请选择相同供应商的单据");
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      if (!this.ids.length) {
        this.$message.error("请勾选要导出的出库单");
        return;
      }
      var idsArr = [];
      for (var i = 0; i < this.ids.length; i++) {
        var item = this.ids[i];
        var obj = {
          outboundId: item,
        };
        idsArr.push(obj);
      }
      this.downloadExcel(
        "md/outbound/export",
        idsArr,
        `出库单_${new Date().getTime()}.xlsx`
      );
      this.$refs.tableList.clearSelection();
    },
    handleDelete(row) {
      const deleData = row.outboundId || this.ids;
      this.$confirm("是否确认删除，此操作不可逆, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        request({
          url: "/md/outbound/" + deleData,
          method: "delete",
        }).then((res) => {
          if (res.code == 200) {
            this.$message.success("操作成功");
            this.getList();
          } else {
            this.$message.error(res.msg || "操作失败");
          }
        });
      });
    },
    handlechange(row) {
      const datarow = { ...row } || null;
      this.detailopen = {
        show: true,
        data: datarow,
      };
    },
    handleBatch() {
      if (this.selRow.length == 0) {
        this.$message.error("请勾选单据");
        return;
      }
      this.recipient = "";
      this.openBatch = true;
    },
    async submitBatch() {
      let promiseList = [];
      for (var i = 0; i < this.selRow.length; i++) {
        var item = this.selRow[i];
        let promise = new Promise((resolve, reject) => {
          item.destination = this.recipient;
          request({
            url: "/md/outbound",
            method: "put",
            data: item,
          }).then((res) => {
            if (res.code == 200) {
              resolve(res || "操作成功");
            } else {
              reject(res.msg || "操作失败");
            }
          });
        });
        promiseList.push(promise);
      }
      await Promise.all(promiseList)
        .then((res) => {
          // 等所有异步请求完成后执行
          this.$modal.msgSuccess(res.msg || "操作成功");
          this.openBatch = false;
        })
        .catch((er) => {
          this.$message.error(er || "操作失败！");
        })
        .finally(() => {
          this.getList();
        });
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    //期初导入
    handleImport() {
      this.upload.title = "期初导入";
      this.upload.open = true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },
  },
  filters: {
    dateFormat(dataStr) {
      if (!dataStr) {
        return;
      }
      var dt = new Date(dataStr);
      var y = dt.getFullYear();
      var m = (dt.getMonth() + 1).toString().padStart(2, "0");
      var d = dt.getDate().toString().padStart(2, "0");
      var hh = dt.getHours().toString().padStart(2, "0");
      var mm = dt.getMinutes().toString().padStart(2, "0");
      var ss = dt.getSeconds().toString().padStart(2, "0");
      return `${y}-${m}-${d}`;
    },
  },
};
</script>
